<template>
  <div class="container">
    <div style="margin: 20px 0">
      <!--     地址部分-->
      <el-card style="padding: 0 10px">
        <strong>收货地址</strong>
        <Address ref="address"></Address>
      </el-card>
      <!--     商品列表部分-->
      <el-card style="margin: 10px 0">
        <div class="shopping-cart">
          <strong>购物清单</strong>
          <el-table
              ref="multipleTable"
              :data="productList"
              style="width: 100%"
          >
            <el-table-column label="商品信息" min-width="228">
              <template slot-scope="scope">
                <div class="product-info">
                  <el-image
                      :src="scope.row.defaultPic"
                      :preview-src-list="[scope.row.defaultPic]"
                      style="width: 80px; height: 80px"
                  ></el-image>
                  <span class="product-name">{{ scope.row.productName }}</span>
                </div>
              </template>
            </el-table-column>


            <el-table-column prop="spec" label="规格" width="150">
              <template #default="{row,$index}">
                {{ skuData(row) }}
              </template>
            </el-table-column>

            <el-table-column label="单价" width="150">
              <template slot-scope="scope">
                <span>¥{{ scope.row.price }}</span>
              </template>
            </el-table-column>

            <el-table-column label="折扣" width="150">
              <template slot-scope="scope">
                <span>{{ scope.row.promotionName ? scope.row.promotionName : "无" }}</span>
              </template>
            </el-table-column>

            <el-table-column label="折扣金额" width="150">
              <template slot-scope="scope">
                <span style="color: red">{{ scope.row.promotionAmount ? scope.row.promotionAmount : "无" }}</span>
              </template>
            </el-table-column>

            <el-table-column label="数量" width="150" align="center">
              <template #default="{ row, $index }">
                <span style="margin: 0 5px">{{ row.quantity }}</span>
              </template>
            </el-table-column>

            <el-table-column label="小计" width="150">
              <template slot-scope="scope">
                <span class="subtotal" v-if="scope.row.totalPrice">¥{{
                    (scope.row.totalPrice * scope.row.quantity).toFixed(2)
                  }}</span>
                <span class="subtotal" v-else>¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}</span>
              </template>
            </el-table-column>
          </el-table>
          <div>
            <div class="coupon-container" v-if="coupons.length!=0">
              <strong>优惠卷</strong>
              <!--            <el-radio-group v-model="selectedCoupon">-->
              <el-row :gutter="20">
                <el-col :span="8" v-for="(coupon,index) in coupons" :key="coupon.id">
                  <div class="coupon" :class="{'checkStyle':checkCoupon==index}" @click="check(index,coupon)">
                    <span style="position: relative;right: 0;" v-if="checkCoupon==index">
                        <i class="el-icon-check"></i>
                    </span>

                    <div class="coupon-content">
                      <h3 class="coupon-name">{{ coupon.name }}</h3>
                      <p class="coupon-amount">金额：<span class="highlight">{{ coupon.amount }}元</span></p>
                      <p class="coupon-amount">满：<span class="highlight">{{ coupon.minPoint }}元可用</span></p>
                      <p class="coupon-period">有效期：{{ coupon.startTime }} 至 {{ coupon.endTime }}</p>
                      <p class="coupon-note">备注：{{ coupon.note }}</p>
                      <p class="coupon-type">类型：<span v-if="coupon.type == 1" class="highlight">满减券</span><span v-else
                                                                                                                class="highlight">折扣券</span>
                      </p>
                      <p class="coupon-min-point">最低消费：{{ coupon.minPoint }}元</p>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>

          <div class="cart-footer">
            <div class="footer-right">
              <div class="total-amount">
              <span>
                总金额：<span class="amount">¥{{ totalAmount }}</span>
              </span>
                <span style="margin:  0 20px" v-if="integral!=0">
                   <el-checkbox v-model="integralChecked" @change="integralCheckedChange">
                我的积分：<span class="amount" style="color: red">{{ integral }}</span>&nbsp;&nbsp;(1元兑换100积分)
                     </el-checkbox>
              </span>
                <span style="margin: 0 20px">
                支付金额：<span class="amount">¥{{ payPrice }}</span>
              </span>
              </div>

              <el-button type="primary" @click="gotoPay">立即支付</el-button>
            </div>
          </div>
        </div>
      </el-card>
      <goback :right="40" :bottom="120"/>
    </div>
  </div>

</template>

<script>
import Address from "@/components/order/Address";
import base64 from "@/utils/base64";
export default {
  components: {
    Address
  },
  data() {
    return {
      cartItems: [],
      selectedCoupon: null,
      coupons: [],
      checkCoupon: 1000,
      productList: [],
      payPrice: 0,
      // 积分
      integral: 0,
      integralChecked: false,
      SelectCoupon: {}
    }
  },
  computed: {
    totalAmount() {
      return this.productList.reduce((sum, item) => {
        let i = 0;
        if (item.totalPrice != null) {
          i = (item.totalPrice * item.quantity)
        } else {
          i = (item.price * item.quantity)
        }
        return sum + i
      }, 0)
    },

  },
  created() {
    this.cartItems = JSON.parse(this.$route.query.list)
    this.getCouponList()
    this.getCartProduct()
    this.integral = this.$store.state.UserInfo?.integration
  },
  methods: {
    integralCheckedChange(val) {
      let price = (this.integral / 100).toFixed(2)
      if (val) {
        this.payPrice = (this.payPrice - price).toFixed(2)
      } else {
        this.payPrice = (this.payPrice * 1) + (price * 1)
      }
    },
    getCartProduct() {
      let ids = this.cartItems.map(i => i.productId)
      this.$api.order.getCartProductList(ids.join(",")).then(res => {
        if (res.code == 200) {
          this.productList = res.data
          this.payPrice = this.productList.reduce((sum, item) => {
            let i = 0;
            if (item.totalPrice != null) {
              i = (item.totalPrice * item.quantity)
            } else {
              i = (item.price * item.quantity)
            }
            return sum + i
          }, 0)
        }
      })
    },
    //选中的优惠卷
    check(index, row) {
      if (row.minPoint > this.totalAmount) {
        return this.$message.warning("不满足该卷使用需求~")
      }
      if (this.checkCoupon == index) {
        this.checkCoupon = 1000
        if (this.integralChecked) {
          this.payPrice = (this.totalAmount - (this.integral / 100)).toFixed(2)
        } else {
          this.payPrice = this.totalAmount
        }
        this.SelectCoupon = {}
      } else {
        this.SelectCoupon = row
        this.checkCoupon = index
        this.payPrice = (this.payPrice - row.amount).toFixed(2)
      }
    },
    getCouponList() {
      this.$api.order.couponListByOrder(this.cartItems).then(res => {
        if (res.code == 200) {
          this.coupons = res.data
          // 默认选择第一个优惠卷
          if (this.coupons.length > 0) {
            this.selectedCoupon = this.coupons[0].id;
          }
        }
      })
    },

    skuData(row) {
      if (row.productAttr == null || row.productAttr == '') {
        return "单卖无规格";
      }
      let data = JSON.parse(row.productAttr)
      return data.map(item => {
        return item.key + ":" + item.value
      }).join(";")
    },
    handleCouponChange(value) {
      // 当选择优惠卷发生变化时，这里可以添加处理逻辑
      console.log("选中的优惠卷ID:", value);
    },
    applyCoupon() {
      // 这里可以添加应用优惠卷的逻辑
      const selected = this.coupons.find(coupon => coupon.id === this.selectedCoupon);
      if (selected) {
        console.log("应用优惠卷：", selected.name);
        // 可以在这里触发事件或调用父组件的方法来应用优惠卷
        this.$emit('apply-coupon', selected);
      } else {
        console.log("请选择一个优惠卷");
      }
    },
    gotoPay() {
      let from = {}
      from.productIds= this.productList.map(item => {
        return item.productId
      })
      from.useCoupon = this.checkCoupon == 1000 ? false : true
      from.couponId = this.SelectCoupon.couponId || null
      from.useIntegration = this.integralChecked
      let address = this.$refs.address.getDefaultAddress()
      if (address.id == undefined || address.id == null) {
        this.$message.warning("请设设置默认地址~")
        return
      }
      from.addressId=address.id
      this.$api.order.createOrder(from).then(res=>{
        if (res.code==200){
          this.$router.push({
            path: '/payPrice',
            query: {
              orderId:base64.encode(JSON.stringify(res.data))
            }
          })
        }
      })

    }
  }
}
</script>
<style scoped lang="less">
.cart-footer {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
}

.product-name {
  position: relative;
  top: -30px;
  margin: 0 2px;
  font-size: 14px;
  color: #333;
}

.footer-right {
  display: flex;
  align-items: center;
  gap: 20px;
}


//-----------------------
.coupon-container {
  margin: 10px 0;
}

.coupon {
  border: 1px solid gainsboro;
  padding: 10px;
  background-color: gainsboro;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-bottom: 10px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.checkStyle {
  //border: 1px solid rgb(138, 182, 96)!important;
  background-color: rgb(138, 182, 96) !important;
}

.coupon:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.coupon-content {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  width: 100%;
}

.coupon-name {
  color: #4CAF50;
  margin-bottom: 5px;
}

.coupon-amount {
  font-size: 14px;
  margin-bottom: 3px;
}

.coupon-period {
  font-size: 12px;
  margin-bottom: 3px;
}

.coupon-note {
  font-size: 12px;
  margin-bottom: 3px;
}

.coupon-type {
  font-size: 12px;
  margin-bottom: 3px;
}

.coupon-min-point {
  font-size: 12px;
  margin-bottom: 3px;
}

.highlight {
  color: #4CAF50;
  font-weight: bold;
}

.el-radio {
  display: flex;
  align-items: center;
}

.el-radio__input {
  margin-right: 10px;
}

.apply-button-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.el-button {
  width: 200px;
}

/deep/ .el-radio-group {
  display: inline;
}

</style>